package com.heima.article.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.service.ApArticleService;
import com.heima.common.contants.ArticleContants;
import com.heima.model.aritlce.dto.ArticleDto;
import com.heima.model.aritlce.dto.ArticleHomeDto;
import com.heima.model.aritlce.pojo.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dto.PageSearchArticleDto;
import com.heima.model.search.pojo.SearchArticleVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(path = "/api/v1/article")
public class ArticleController {

    @Resource
    private ApArticleService apArticleService;

    @PostMapping(path = "/save")
    @ApiOperation("保存APP端文章数据")
    public ResponseResult saveArticle(@RequestBody ArticleDto dto) {
        ApArticle apArticle = apArticleService.saveArticle(dto);
        return ResponseResult.success(apArticle.getId());
    }

    @PostMapping(path = "/load")
    @ApiOperation("首页默认加载推荐频道列表")
    public ResponseResult<List<ApArticle>> load(@RequestBody ArticleHomeDto dto) {
        List<ApArticle> articleList = apArticleService.load(dto, ArticleContants.LOAD_TYPE_MORE);
        return ResponseResult.success(articleList);
    }

    @PostMapping(path = "/loadmore")
    @ApiOperation("加载更多文章")
    public ResponseResult<List<ApArticle>> loadmore(@RequestBody ArticleHomeDto dto) {
        List<ApArticle> articleList = apArticleService.load(dto, ArticleContants.LOAD_TYPE_MORE);
        return ResponseResult.success(articleList);
    }

    @PostMapping(path = "/loadnew")
    @ApiOperation("加载最最新文章")
    public ResponseResult<List<ApArticle>> loadnew(@RequestBody ArticleHomeDto dto) {
        List<ApArticle> articleList = apArticleService.load(dto, ArticleContants.LOAD_TYPE_NEW);
        return ResponseResult.success(articleList);
    }

    /***
     * 批量导入分页查询数据接口
     */
    @GetMapping("/importData/{page}/{size}")
    public PageSearchArticleDto pageData(@PathVariable("page")Integer page, @PathVariable("size")Integer size){
        //1、分页查询【注意，这里如果要做的更完善，可以添加限制条件，比如已上架】
        Page<ApArticle> pageInfo = apArticleService.lambdaQuery()
                .page(new Page<ApArticle>(page, size));
        //2、封装DTO
        List<SearchArticleVo> list = pageInfo.getRecords().stream()
                //ApArticle转换SearchArticleVo
                .map(article -> BeanUtil.copyProperties(article, SearchArticleVo.class))
                .collect(Collectors.toList());
        return PageSearchArticleDto.builder()
                .total(pageInfo.getTotal())
                .totalPages(pageInfo.getPages())
                .articleVos(list)
                .build();
    }
}
